package com.dldata.devtools30.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by 呵呵 on 2017-10-25.
 */
public class DBTypeUtil {

    private final static Logger logger = LoggerFactory.getLogger(DBTypeUtil.class);

    public static enum DBTYPE{
        h2,mysql,oracle,postgresql,sqlserver
    }

    public static DBTYPE getDbtype(DataSource dataSource) {
        String jdbcUrl = null;
        int i=0;
        while(i<=3&&jdbcUrl==null){
            try{
                jdbcUrl = getJdbcUrlFromDataSource(dataSource);
            }catch (Throwable var11){
                if(var11.getCause()!=null){
                    logger.error(var11.getCause().getMessage()+"  DataSource [" + dataSource + "]",var11.getCause());
                }
                logger.error(var11.getMessage()+"  DataSource [" + dataSource + "]",var11);
            }
        }
        return getDbtype(jdbcUrl);
    }

    public static DBTYPE getDbtype(String jdbcUrl) {
        if(StringUtils.contains(jdbcUrl, ":h2:")) {
            return DBTYPE.h2;
        } else if(StringUtils.contains(jdbcUrl, ":mysql:")) {
            return DBTYPE.mysql;
        } else if(StringUtils.contains(jdbcUrl, ":oracle:")) {
            return DBTYPE.oracle;
        } else if(StringUtils.contains(jdbcUrl, ":postgresql:")) {
            return DBTYPE.postgresql;
        } else if(StringUtils.contains(jdbcUrl, ":sqlserver:")) {
            return DBTYPE.sqlserver;
        } else {
            throw new IllegalArgumentException("Unknown Database of " + jdbcUrl);
        }
    }

    private static String getJdbcUrlFromDataSource(DataSource dataSource) {
        Connection connection = null;
        String e = null;
        try {
            connection = DataSourceUtils.getConnection(dataSource);
            if(connection == null) {
                throw new IllegalStateException("Connection returned by DataSource [" + dataSource + "] was null");
            }

            e = connection.getMetaData().getURL();
        } catch (SQLException var11) {
            if(var11.getCause()!=null){
                logger.error(var11.getCause().getMessage()+"  DataSource [" + dataSource + "]",var11.getCause());
            }
            logger.error(var11.getMessage()+"  DataSource [" + dataSource + "]",var11);
            throw new RuntimeException("Could not get database url", var11);
        } finally {
            DataSourceUtils.releaseConnection(connection,dataSource);
        }

        return e;
    }
}
